package com.zf.shuashua.ui.home;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.apsara.alivclittlevideo.net.data.LittleMineVideoInfo;
import com.aliyun.apsara.alivclittlevideo.sts.OnStsResultListener;
import com.aliyun.apsara.alivclittlevideo.sts.StsInfoManager;
import com.aliyun.apsara.alivclittlevideo.view.video.BaseVideoSourceModel;
import com.aliyun.apsara.alivclittlevideo.view.video.OnStsInfoExpiredListener;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.AlivcVideoListView;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.IVideoSourceModel;
import com.aliyun.apsara.alivclittlevideo.view.video.videolist.RecyclerViewEmptySupport;
import com.aliyun.common.utils.DensityUtil;
import com.aliyun.svideo.base.sts.StsTokenInfo;
import com.aliyun.svideo.common.utils.NetUtils;
import com.aliyun.svideo.common.utils.ScreenUtils;
import com.app.hubert.guide.NewbieGuide;
import com.app.hubert.guide.core.Builder;
import com.app.hubert.guide.core.Controller;
import com.app.hubert.guide.listener.OnLayoutInflatedListener;
import com.app.hubert.guide.model.GuidePage;
import com.app.hubert.guide.model.HighLight;
import com.app.hubert.guide.model.HighlightOptions;
import com.app.hubert.guide.model.RelativeGuide;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.core.widget.webview.SSWebView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.mediamain.android.view.FoxWallView;
import com.mediamain.android.view.bean.MessageData;
import com.mediamain.android.view.interfaces.FoxListener;
import com.meis.base.mei.base.BaseFragment;
import com.meis.base.mei.status.ViewState;
import com.meis.base.mei.utils.NumberUtils;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.MainActivity;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdReportManager;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.AdvertReportManager;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.InteractionAdListener;
import com.zf.shuashua.advert.NativeAdvertManager;
import com.zf.shuashua.advert.OnRewardListener;
import com.zf.shuashua.advert.RewardAdvertManager;
import com.zf.shuashua.advert.TTAdManagerHolder;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.AdvertInfo;
import com.zf.shuashua.bean.AdvertList;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.bean.BannerBean;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.ButtleDoubleStatus;
import com.zf.shuashua.bean.ExtraBean;
import com.zf.shuashua.bean.GoldBean;
import com.zf.shuashua.bean.HotVSHome;
import com.zf.shuashua.bean.Reward;
import com.zf.shuashua.bean.ToShare;
import com.zf.shuashua.bean.VideoInfo;
import com.zf.shuashua.bean.VideoPointInfo;
import com.zf.shuashua.bean.advert.AdvertConfigBean;
import com.zf.shuashua.common.ARouter;
import com.zf.shuashua.common.PhoneCallManager;
import com.zf.shuashua.event.GuideGoldVideoEvent;
import com.zf.shuashua.event.UpdateCommentNumberEvent;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.manager.AdDownloadManager;
import com.zf.shuashua.manager.ReportVideoTagManager;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.custom.CountDownView;
import com.zf.shuashua.ui.custom.RxBus;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.home.search.SearchActivity;
import com.zf.shuashua.ui.mine.FriendsDetailsActivity;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.ui.mine.notice.MessageActivity;
import com.zf.shuashua.ui.popup.AutoPlayPopup;
import com.zf.shuashua.ui.popup.ButtleLimitPopup;
import com.zf.shuashua.ui.popup.ButtlePopup;
import com.zf.shuashua.ui.popup.CommonPopup;
import com.zf.shuashua.ui.popup.LoginPopup;
import com.zf.shuashua.ui.popup.NetworkBGPopup;
import com.zf.shuashua.ui.popup.OnPopupListener;
import com.zf.shuashua.ui.popup.OpenNoticePopup;
import com.zf.shuashua.utils.MyToast;
import com.zf.shuashua.utils.TimeUtils;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.utils.UIUtils;
import com.zf.shuashua.utils.Util;
import com.zf.shuashua.utils.ValueAnimatorUtil;
import com.zf.shuashua.video.AlivcVideoPlayView;
import com.zf.shuashua.video.LittleVideoListAdapter;
import com.zf.shuashua.widget.GoldLayoutView;
import com.zf.shuashua.widget.RedHeartLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.disposables.Disposable;

public class HomeFragment extends BaseFragment implements PhoneCallManager.CallListener {

    private final static int MESSAGE_WHAT_ANIMATION_END = 1;
    private final static int MESSAGE_WHAT_SHOW_VALUE = 2;
    private final static int MESSAGE_WHAT_GET_CONFIG = 3;

    private HomeViewModel homeViewModel;

    private ImageView imgReward, imgRed;

    private TextView txtReward;

    private CountDownView ctdView;

    private AlivcVideoPlayView videoPlayView;

    private boolean isFirstLoadData = true;

    private static long tempTimeDefault = -1;

    private static int page = 1;
    private int pageSize = ShuaApplication.adRefreshRate;
    private static final int MAY_REQUEST_AD_NUM = 3;

    private boolean hasPopRed;

    private long startTime;

    // 自动播放
    private ImageView ivGuide1;
    private View viewGuide;
    private String mCodeId = "945413530";
    private int currentPosition = 0;

    private boolean isShowTuia = false;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_WHAT_ANIMATION_END:
                    //animation.cancel();
                    break;
                case MESSAGE_WHAT_SHOW_VALUE:
//                    txtReward.startAnimation(textAnimation);
                    break;
                case MESSAGE_WHAT_GET_CONFIG:
                    homeViewModel.fetchConfigInfo();
                    break;
            }

            return false;
        }
    });

    private RedHeartLayout mRedHeartLayout;
    private TTAdNative mTTAdNative;
    private Handler mTTHandler = new Handler(Looper.getMainLooper());
    private List<TTNativeExpressAd> ttNativeExpressAds = new ArrayList<>();

    private boolean isShowAutoPlayView = false;
    private boolean isAutoPlay = false;

    private List<AdvertInfo> adExpressList = new ArrayList<>();
    private String adExpressUUId = "";
    private static boolean isLoadFirstPageAdData = false;
    private boolean isNoticeVideo = false;

    // 金币弹跳视图
    private GoldLayoutView glView;
    private ImageView imgButtleGuide;
    //一个的时候谈手势
    private boolean buttleFirstGuide;
    //六个的时候谈手势
    private boolean buttleLastGuide;

    private ImageView ivPublish;
    private ImageView autoPlay;

    private RelativeLayout flContainer;
    private FrameLayout flGold;
    private boolean isClickGoldEnable = true;
    private ValueAnimator weltAnimator;
    private float dragX;
    private float dragY;

    private ValueAnimator weltAnimator1;
    private boolean isClickGoldEnable1 = true;
    private float dragX1;
    private float dragY1;

    private long lastTime = 0;
    private int tab = -1;
    private Disposable subscribe;
    private FoxWallView mOxWallView;
    private ImageView icDwj;
    private boolean isGuide = true;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        Date now = new Date();
        if (!Store.getInstance().getPaopaoTime().equals(TimeUtils.dateToStr(now))) {
            Store.getInstance().setisPaopaoTime(TimeUtils.dateToStr(now));
            Store.getInstance().setGoldGuideEnable(true);
        }

        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        PhoneCallManager.getInstance().addCallListener(this);
        mTTAdNative = TTAdManagerHolder.get().createAdNative(this.mActivity);
        setupBaseView();
        buttleFirstGuide = Store.getInstance().getButtleFirstGuide();
        buttleLastGuide = Store.getInstance().getButtleLastGuide();
        icDwj = findViewById(R.id.icDwj);

        //初始化播放器列表
        initVideoPlayView(getView());
        //同步广告配置信息
        syncAdvertSource();
        //监听liveData数据
        observeLiveData();
        //金豆转圈监听
        observeCountView();
        //获取初始化配置
        homeViewModel.fetchConfigInfo();
        //无网络时的默认界面
        if (!NetUtils.isNetworkConnected(mActivity)) {
            setState(ViewState.ERROR);
        }
        ctdView.postDelayed(() -> {
            glView.setDefaultStartHeight((int) flGold.getY());
        }, 600);
        //点击领取金豆
        glView.setOnItemClickListener(this::requestGoldPre);
        //新手引导
//        requestUserGuide();
        //金豆转圈
        setupGoldCircle();
        //活动按钮
        setUpDwj();
        mOxWallView = (FoxWallView) findViewById(R.id.TMAw1);
        initFoxView();
        initRewardGuide();
        initNewLockVideoGuide();
    }

    @Override
    protected void initData() {
        subscribe = RxBus.getInstance().toObservable(HotVSHome.class).subscribe(hotVSHome -> {
            tab = hotVSHome.getTab();
        });
        if (Store.getInstance().isLogin()) {
            HttpData.getInstance().getReward(new ACallback<BaseData<Reward>>() {
                @Override
                public void onSuccess(BaseData<Reward> data) {
                    if (data.isStatus() && data.getCode() == 200) {
                        if (data.getData().isPopup() && !TextUtils.isEmpty(data.getData().getBanner())) {
                            NetworkBGPopup popupView = new NetworkBGPopup(mActivity, data.getData().getBanner());
                            new XPopup.Builder(mActivity)
                                    .asCustom(popupView)
                                    .show();
                        }
                    }
                }

                @Override
                public void onFail(int errCode, String errMsg) {
                }
            });
        }
        getFoxSource();
    }

    @Override
    public void onResume() {
        super.onResume();
        ValueAnimatorUtil.resetDurationScale();
    }

    /**
     * 首页悬浮按钮（自身活动或者推啊广告）
     */
    private void getFoxSource() {
        HttpData.getInstance().getUserBannerList("2", new ACallback<String>() {
            @Override
            public void onSuccess(String data) {
                try {
                    List<BannerBean> bannerList = ParseJsonUtils.parseListData(data, "data", BannerBean.class);
                    if (bannerList != null && bannerList.size() > 0) {
                        BannerBean banner = bannerList.get(0);
                        if (banner.isTuia()) {
                            isShowTuia = true;
                            showTuia();
                        } else {
                            isShowTuia = false;
                            mOxWallView.setVisibility(View.GONE);
                            icDwj.setVisibility(View.VISIBLE);
                            Glide.with(mActivity).load(banner.banner_url)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .into(icDwj);

                            icDwj.setOnClickListener(view -> {
                                if (icDwj.getVisibility() == View.VISIBLE && isClickGoldEnable1) {
                                    if (!Store.getInstance().isLogin()) {
                                        mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
                                    } else {
                                        startActivity(new Intent(mActivity, H5Activity.class).putExtra("money", Constants.H5_URL + banner.jump_link).putExtra("title", banner.banner_name));
                                    }
                                }
                            });
                        }
                    }
                } catch (Exception ignored) {

                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });
    }

    /**
     * 推啊悬浮按钮
     */
    private void initFoxView() {
        mOxWallView.setAdListener(new FoxListener() {
            @Override
            public void onReceiveAd() {
                Log.d("========", "onReceiveAd");
            }

            @Override
            public void onFailedToReceiveAd(int errorCode, String errorMsg) {
                Log.d("========", "onFailedToReceiveAd  Message=" + errorMsg);
            }

            @Override
            public void onLoadFailed() {
                Log.d("========", "onLoadFailed");
            }

            @Override
            public void onCloseClick() {
                Log.d("========", "onCloseClick");
            }

            @Override
            public void onAdClick() {
                Log.d("========", "onAdClick");
            }

            @Override
            public void onAdExposure() {
                Log.d("========", "onAdExposure");
            }

            @Override
            public void onAdActivityClose(String s) {
                Log.d("========", "onAdActivityClose" + s);
//                if (!FoxBaseCommonUtils.isEmpty(s)){
//                    ToastUtils.showShort(s);
//                }
            }

            @Override
            public void onAdMessage(MessageData messageData) {

            }

        });
//        if(mOxWallView != null){
//            String userId = Store.getInstance().getuserId();
//            if(TextUtils.isEmpty(userId)){
//                userId = Util.getDeviceId(ShuaApplication.getContext());
//            }
//            mOxWallView.loadAd(361361,userId);
//        }
    }

    private void showTuia() {
        if (!isShowTuia) {
            return;
        }
        mOxWallView.setVisibility(View.VISIBLE);
        icDwj.setVisibility(View.GONE);
        if (mOxWallView != null) {
            mOxWallView.post(() -> {
                String userId = Store.getInstance().getuserId();
                if (TextUtils.isEmpty(userId)) {
                    userId = Util.getDeviceId(ShuaApplication.getContext());
                }
                mOxWallView.loadAd(361361, userId);
            });
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
//        if (buttleFirstGuide) {
//            initClickBubbleGuide();
//        }
        playHandler.removeMessages(1);
        playHandler.removeCallbacksAndMessages(null);
        if (videoPlayView != null) {
            videoPlayView.onResume();
        }
//        showTuia();
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (videoPlayView != null) {
            videoPlayView.onPause();
            playHandler.sendEmptyMessageDelayed(1, 600);
            playHandler.sendEmptyMessageDelayed(1, 1200);
        }
        ctdView.pause();
    }

    @Override
    public void onErrorRetry() {
        super.onErrorRetry();
        if (NetUtils.isNetworkConnected(mActivity)) {
            fetchHomeData(1);
            homeViewModel.fetchConfigInfo();
            setState(ViewState.COMPLETED);
        } else {
            Toast.makeText(mActivity, "请检查网络连接", Toast.LENGTH_SHORT).show();
        }
    }

    private void setupBaseView() {
        getView().findViewById(R.id.view_record).setOnClickListener(v -> {
            glView.addGoldChildView("66");
        });

        flContainer = getView().findViewById(R.id.rl_container);
        imgReward = getView().findViewById(R.id.reward_view);
        flGold = getView().findViewById(R.id.fl_gold);
        imgRed = getView().findViewById(R.id.img_red);
        ctdView = getView().findViewById(R.id.count_down_view);
        imgButtleGuide = getView().findViewById(R.id.img_buttle_guide);
        //imgButtleGuide.setVisibility(View.GONE);
        txtReward = getView().findViewById(R.id.reward_money);
        mRedHeartLayout = getView().findViewById(R.id.red_heart);
        autoPlay = getView().findViewById(R.id.auto_play);

        ivGuide1 = getView().findViewById(R.id.iv_guide1);
        viewGuide = getView().findViewById(R.id.view_guide);

        glView = getView().findViewById(R.id.gl_view);
        ivPublish = getView().findViewById(R.id.iv_publish);

        ivPublish.setOnClickListener(v -> jumpToRecorder());

        if (isShowAutoPlayView) {
            autoPlay.setVisibility(View.VISIBLE);
        } else {
            autoPlay.setVisibility(View.INVISIBLE);
        }
        switchAutoPlayImage();
        autoPlay.setOnClickListener(v -> {
            if (!Store.getInstance().isLogin()) {
                mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
            } else {
                // false 弹框
                if (!isAutoPlay) {
                    showAutoPlayPopup();
                    reportAdvertAction(TrackConstants.ACTION_HOME_AUTOPLAY, TrackConstants.NOTE_HOME_AUTOPLAY);
                } else {
                    autoPlayClick(false);
                    reportAdvertAction(TrackConstants.ACTION_HOME_MANUAL, TrackConstants.NOTE_HOME_MANUAL);
                }
            }
        });

        mRedHeartLayout.setOnHartClickListener(() -> {
            if (videoPlayView != null) {
                videoPlayView.onHartClick();
            }
        });
        //搜索
        getView().findViewById(R.id.search).setOnClickListener(v -> {
            Intent intent = new Intent();
            if (mActivity != null) {
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_HOME_SEARCH, TrackConstants.NOTE_HOME_SEARCH);
                intent.setClass(mActivity, SearchActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * liveData监听
     */
    private void observeLiveData() {
        homeViewModel.getHomeData().observe(this, result -> {
            if (result != null && result.getMeta() != null) {
                changeVideoAutoPlay(result.getMeta().isVideo_auto_play_status());
            }
            ArrayList<LittleMineVideoInfo.VideoListBean> videoList = new ArrayList<>();
            int index = 0;
            int indexAd = 0;
            boolean isSelf = false;
            for (VideoInfo dataBean : result.getData()) {
                index++;
                LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
                videoListBean.setVideoId(dataBean.getMedia_id());
                videoListBean.setVideoUrl(dataBean.getMedia_url());
                videoListBean.setFirstFrameUrl(dataBean.getAvatar());
                videoListBean.setDescription(dataBean.getDescription());
                BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
                if (dataBean.getUser() != null) {
                    userBean.setAvatarUrl(dataBean.getUser().getAvatar());
                    userBean.setUserId(dataBean.getUser().getId() + "");
                    userBean.setUserName(dataBean.getUser().getName());
                }
                videoListBean.setUser(userBean);
                videoListBean.setType(dataBean.getType());
                videoListBean.setId(dataBean.getId());
                videoListBean.setShareUrl(dataBean.getMedia_url());
                videoListBean.setTitle(dataBean.getTitle());
                videoListBean.setLocation(dataBean.getLocation());
                videoListBean.setCommentCount(dataBean.getComment_count());
                videoListBean.setPraiseCount(dataBean.getPraise_count());
                videoListBean.setForwardCount(dataBean.getForward_count());
                videoListBean.setLove(dataBean.getIs_praise_user());
                videoListBean.setLength(dataBean.getLength());
//                if (!isFirstLoadData && ShuaApplication.isEnable_advert_middle) {
                if (!isFirstLoadData) {
                    if (ShuaApplication.drawConfig != null) {
                        if (ttNativeExpressAds.size() > 0) {
                            if (index != 0 && index % pageSize == 0 && indexAd < ttNativeExpressAds.size()) {
                                videoList.add(coverAdToVideoBean(ttNativeExpressAds.get(indexAd)));
                                indexAd++;
                            }
                            isSelf = false;
                        } else {
                            if (index != 0 && index % pageSize == 0 && indexAd < adExpressList.size()) {
                                videoList.add(coverOwnAdToVideoBean(adExpressList.get(indexAd), adExpressUUId));
                                indexAd++;
                            }
                            isSelf = true;
                        }
                    }
                }
                videoList.add(videoListBean);
            }
            if (isSelf) {
                adExpressList = new ArrayList<>();
            } else {
                ttNativeExpressAds = new ArrayList<>();
            }
            if (isNoticeVideo && videoListBean != null) {
                videoList.add(0, videoListBean);
                videoListBean = null;
                isNoticeVideo = false;
            }
            if (isFirstLoadData) {
                if (videoPlayView != null) {
                    videoPlayView.refreshVideoList(videoList, 0);
                }
                isFirstLoadData = false;

            } else {
                if (videoPlayView != null) {
                    videoPlayView.addMoreData(videoList);
                }
            }

            if (ShuaApplication.drawConfig != null) {
                mTTHandler.postDelayed(this::loadAdvertList, 500);
            }

        });
        homeViewModel.getVideoPointInfo().observe(this, videoPointInfoBaseData -> {
            if (videoPointInfoBaseData != null && videoPointInfoBaseData.getData() != null) {
//                int tempTime = -1;
                VideoPointInfo videoPointInfo = videoPointInfoBaseData.getData();
                if (videoPointInfo == null || videoPointInfo.getValue() == null) {
                    return;
                }
//                String pointTime = videoPointInfo.getVideo_play_get_point_time();
//                if (!TextUtils.isEmpty(pointTime)) {
//                    try {
//                        tempTime = Integer.parseInt(pointTime) * 1000;
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
                int num = Integer.parseInt(videoPointInfo.getValue());
//                txtReward.setText("+" + num + "金豆");
                if (glView != null) {
//                    int num = 60 + new Random().nextInt(41);
                    try {
                        //第一个泡泡弹出的时候手势指引
                        if (!buttleFirstGuide && glView.getChildCount() == 0) {
//                            initGuide();
                            initClickBubbleGuide();
                            glView.postDelayed(() -> {
                                // imgButtleGuide.setVisibility(View.VISIBLE);
//                                Glide.with(this).asGif().load(R.drawable.ic_buttl_guide)
//                                        .diskCacheStrategy(DiskCacheStrategy.NONE)
//                                        .into(imgButtleGuide);
                                buttleFirstGuide = true;
                                Store.getInstance().setButtleFirstGuide(true);
                            }, 1600);
                        }
                        //第六个泡泡弹出的时候手势指引
                        if (!buttleLastGuide && glView.getChildCount() == 5 && imgButtleGuide.getVisibility() != View.VISIBLE) {
                            glView.postDelayed(() -> {
                                // imgButtleGuide.setVisibility(View.VISIBLE);
//                                Glide.with(this).asGif().load(R.drawable.ic_buttl_guide)
//                                        .diskCacheStrategy(DiskCacheStrategy.NONE)
//                                        .into(imgButtleGuide);
                                buttleLastGuide = true;
                                Store.getInstance().setButtleLastGuide(true);
                            }, 1600);
                        }
                    } catch (Exception ignored) {

                    }
                    glView.addGoldChildView(num + "");

                    boolean isGoldGuide = Store.getInstance().isGoldGuide();
                    glView.postDelayed(() -> {
                        imgButtleGuide.setVisibility(isGoldGuide ? View.VISIBLE : View.GONE);
                        if (imgButtleGuide.getVisibility() == View.VISIBLE) {
                            imgButtleGuide.setBackgroundResource(R.drawable.home_gold_guide_click_list);
                            AnimationDrawable animal = (AnimationDrawable) imgButtleGuide.getBackground();
                            animal.start();
                        }
                    }, 1600);
                }
            }
        });
        homeViewModel.getConfigInfo().observe(this, configInfo -> {
            if (configInfo == null) {
                //获取配置失败，重新获取
                mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT_GET_CONFIG, 5000);
                return;
            }
            int tempTime = -1;
            String pointTime = configInfo.getVideo_play_get_point_time();
            if (!TextUtils.isEmpty(pointTime)) {
                try {
                    tempTime = Integer.parseInt(pointTime) * 1000;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (tempTime > 0) {
                tempTimeDefault = tempTime;
                ctdView.setVisibility(View.VISIBLE);
                imgReward.setVisibility(View.VISIBLE);
                if (videoPlayView != null && !videoPlayView.isPause() && videoPlayView.getOnPlayStatusListener() != null) {
                    videoPlayView.getOnPlayStatusListener().start();
                }
            } else {
                ctdView.setVisibility(View.GONE);
                imgReward.setVisibility(View.GONE);
                mHandler.sendEmptyMessageDelayed(MESSAGE_WHAT_GET_CONFIG, 5000);
            }

            try {
                ShuaApplication.multiple_min = Integer.parseInt(configInfo.getMultiple_min());
                ShuaApplication.multiple_max = Integer.parseInt(configInfo.getMultiple_max());
            } catch (Exception e) {

            }

            // 判断是否展示广
//            if (Store.getInstance().isLogin()) {
//                ShuaApplication.isEnable_advert_middle = configInfo.isEnable_advert_middle();
//            }
        });
    }

    /**
     * 金豆转圈
     */
    private void observeCountView() {
        ctdView.setCountDownViewListener(() -> {
            try {
                if (!Store.getInstance().isLogin()) {
                    if (!hasPopRed) {
                        if (Store.getInstance().getNewUserPopup()) {
                            showRedDialog();
                            hasPopRed = true;
                        }
                    } else {
                        ToastUtil.showToast(mActivity, "登录后观看视频即可获得金豆哦");
                    }
                    return;
                }
                if (videoPlayView != null) {
                    BaseVideoSourceModel currentModel = videoPlayView.getCurrentModel();
                    homeViewModel.fetchVideoPointInfo(currentModel);
                }
            } catch (Exception ignored) {

            }
        });
    }

    /**
     * 金豆转圈可移动
     */
    @SuppressLint("ClickableViewAccessibility")
    private void setupGoldCircle() {
        flGold.setOnClickListener(v -> {
            if (imgReward.getVisibility() == View.VISIBLE && isClickGoldEnable) {
                if (Store.getInstance().isLogin()) {
                    ((MainActivity) mActivity).openGift();
                } else {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }
            }
        });
        flGold.setEnabled(true);
        flGold.setOnTouchListener((v, event) -> {
            if (weltAnimator != null && weltAnimator.isRunning()) {
                return false;
            }
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isClickGoldEnable = true;
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    dragX = event.getRawX();
                    dragY = event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - dragX;
                    float dy = event.getRawY() - dragY;

                    if (isClickGoldEnable) {
                        if (Math.abs(dx) >= 5 || Math.abs(dy) >= 5) {
                            isClickGoldEnable = false;
                        }
                    }

                    float x = v.getX() + dx;
                    float y = v.getY() + dy;

                    if (x <= 0) {
                        x = 0;
                    }

                    if (y <= 0) {
                        y = 0;
                    }

                    if (x >= flContainer.getWidth() - v.getWidth()) {
                        x = flContainer.getWidth() - v.getWidth();
                    }

                    if (y >= flContainer.getHeight() - v.getHeight()) {
                        y = flContainer.getHeight() - v.getHeight();
                    }

                    v.setX(x);
                    v.setY(y);

                    dragX = event.getRawX();
                    dragY = event.getRawY();

                    break;
                case MotionEvent.ACTION_UP:
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    int width = flContainer.getWidth();
                    int height = flContainer.getHeight();

                    glView.setDefaultStartHeight((int) v.getY());
                    glView.setDefaultStartWidth((int) v.getX());

                    if (v.getX() == 0 || v.getX() == width - v.getWidth()) {
                        break;
                    }

                    int end = 0;

                    float centerX = v.getX() + v.getWidth() / 2;

                    if (centerX >= width / 2) {
                        end = width - v.getWidth();
                    } else {
                        end = 0;
                    }

                    weltAnimator = ValueAnimator.ofInt((int) v.getX(), end);
                    weltAnimator.setDuration(400);
                    weltAnimator.addUpdateListener(animation -> {
                        int value = (int) animation.getAnimatedValue();
                        v.setX(value);
                    });
                    weltAnimator.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            glView.setDefaultStartHeight((int) v.getY());
                            glView.setDefaultStartWidth((int) v.getX());
                        }
                    });
                    weltAnimator.start();

                    break;
            }
            return false;
        });

    }

    /**
     * 设置活动按钮可移动
     */
    @SuppressLint("ClickableViewAccessibility")
    private void setUpDwj() {
        icDwj.setOnTouchListener((v, event) -> {
            if (weltAnimator1 != null && weltAnimator1.isRunning()) {
                return false;
            }
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isClickGoldEnable1 = true;
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    dragX1 = event.getRawX();
                    dragY1 = event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - dragX1;
                    float dy = event.getRawY() - dragY1;

                    if (isClickGoldEnable1) {
                        if (Math.abs(dx) >= 5 || Math.abs(dy) >= 5) {
                            isClickGoldEnable1 = false;
                        }
                    }

                    float x = v.getX() + dx;
                    float y = v.getY() + dy;

                    if (x <= 0) {
                        x = 0;
                    }

                    if (y <= 0) {
                        y = 0;
                    }

                    if (x >= flContainer.getWidth() - v.getWidth()) {
                        x = flContainer.getWidth() - v.getWidth();
                    }

                    if (y >= flContainer.getHeight() - v.getHeight()) {
                        y = flContainer.getHeight() - v.getHeight();
                    }

                    v.setX(x);
                    v.setY(y);

                    dragX1 = event.getRawX();
                    dragY1 = event.getRawY();

                    break;
                case MotionEvent.ACTION_UP:
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    int width = flContainer.getWidth();
                    int height = flContainer.getHeight();
                    if (v.getX() == 0 || v.getX() == width - v.getWidth()) {
                        break;
                    }

                    int end = 0;

                    float centerX = v.getX() + v.getWidth() / 2;

                    if (centerX >= width / 2) {
                        end = width - v.getWidth();
                    } else {
                        end = 0;
                    }

                    weltAnimator1 = ValueAnimator.ofInt((int) v.getX(), end);
                    weltAnimator1.setDuration(400);
                    weltAnimator1.addUpdateListener(animation -> {
                        int value = (int) animation.getAnimatedValue();
                        v.setX(value);
                    });
                    weltAnimator1.start();

                    break;
            }
            return false;
        });
    }

    /**
     * 同步本地的开关信息到application
     */
    private void syncAdvertSource() {
        Store store = Store.getInstance();
        ShuaApplication.adRefreshRate = store.getAdvertRate();
        ShuaApplication.horizontalRate = store.getHorizontalRate();
        pageSize = ShuaApplication.adRefreshRate;
//        List<AdvertConfigBean> drawList = store.getDrawConfig();
//        if (drawList != null && drawList.size() > 0) {
//            DrawConfigBean drawConfigBean = new DrawConfigBean();
//            drawConfigBean.setDrawing(drawList);
//            if(ShuaApplication.drawConfig == null){
//                drawConfigBean.setIndexDraw(Store.getInstance().getDrawIndex());
//                ShuaApplication.drawConfig = drawConfigBean;
//            }
//        }
//        List<AdvertConfigBean> horizontalList = store.getHorizontalConfig();
//        if (horizontalList != null && horizontalList.size() > 0) {
//            HorizontalConfigBean horizontalConfig = new HorizontalConfigBean();
//            horizontalConfig.setHorizontal(horizontalList);
//            if (ShuaApplication.horizontalConfig == null) {
//                ShuaApplication.horizontalConfig = horizontalConfig;
//            }
//        }
    }

    /**
     * 新手引导
     */
//    private void requestUserGuide() {
//        if (Store.getInstance().isLogin()) {
//            HttpData.getInstance().getUserGuide(new ACallback<String>() {
//                @Override
//                public void onSuccess(String data) {
//                    String status = ParseJsonUtils.parseResponseValue(data, "status");
//                    if (status.equals("true")) {
//                        ctdView.postDelayed(() -> {
//                            GuideEntity.isGuide = true;
//                            GuideEntity guideEntity = new GuideEntity();
//                            guideEntity.level = SPUtils.getInstance().getInt(GuideEntity.GUIDE_LEVEL, 1);
//                            GuideEntity.LEVEL1 l1 = new GuideEntity.LEVEL1();
//                            l1.viewX = (int) flGold.getX();
//                            l1.viewY = (int) flGold.getY();
//                            l1.viewWidth = flGold.getWidth();
//                            l1.viewHeight = flGold.getHeight();
//                            guideEntity.level1 = l1;
//                            startGuide2(guideEntity);
////                            ctdView.startNewUserGuide(tempTimeDefault);
//                            showGuidePoint();
//                        }, 600);
//                    } else if (status.equals("false")) {
//                        GuideEntity.isGuide = false;
//                    }
//                }
//
//                @Override
//                public void onFail(int errCode, String errMsg) {
//                }
//            });
//        }
//    }

    /**
     * 新手引导5s后强制弹出第一个泡泡
     */
    private void showGuidePoint() {
        glView.postDelayed(() -> {
            if (videoPlayView != null) {
                BaseVideoSourceModel currentModel = videoPlayView.getCurrentModel();
                homeViewModel.fetchVideoPointInfo(currentModel);
            }
        }, 5000);
    }

    private ButtlePopup buttlePopup;

    /**
     * 领取金豆
     *
     * @param childIndex
     * @param goldNumber
     */
    private void showGoldPopup(int childIndex, String goldNumber) {
        int randomMultiple = getRandomMultiple();
        glView.startRemoveAnim(childIndex);
        if (buttlePopup != null) {
            buttlePopup.dismiss();
            buttlePopup = null;
        }
        buttlePopup = new ButtlePopup(mActivity, goldNumber, randomMultiple);
        buttlePopup.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                if (buttlePopup != null) {
                    buttlePopup.close();
                }
                checkBubbleDoubleStatus(goldNumber, randomMultiple);
            }

            @Override
            public void onClose() {

            }
        });
        new XPopup.Builder(mActivity)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated() {

                    }

                    @Override
                    public void beforeShow() {

                    }

                    @Override
                    public void onShow() {
                        isRequesting = false;
                    }

                    @Override
                    public void onDismiss() {

                    }

                    @Override
                    public boolean onBackPressed() {
                        return false;
                    }
                })
                .asCustom(buttlePopup)
                .show();

    }

    private void showGoldDoublePop(String goldNumber, int randomMultiple) {
        RewardAdvertManager.getInstance().showAdvert(mActivity, AdvertConstants.REWARD_TYPE_BUBBLE, new OnRewardListener() {
            @Override
            public void onAdClose() {
                HttpData.getInstance().requestGoldReward(Integer.parseInt(goldNumber) * randomMultiple + "", true, new AbsCallback<BaseData<GoldBean>>() {
                    @Override
                    public void onSuccess(BaseData<GoldBean> data) {
                        if (data == null) {
                            return;
                        }
                        if (data.isStatus() && data.getCode() == 200) {
                            onRealSuccess(data);
                        } else {
                            ToastUtil.showInCenter(mActivity, data.getMessage());
                        }
                    }

                    @Override
                    public void onRealSuccess(BaseData<GoldBean> goldBean) {
                        String value = goldBean.getData().getValue();
                        if (!TextUtils.isEmpty(value)) {
                            CommonPopup popup1 = new CommonPopup(mActivity, "额外奖励", "我知道了", value, "0");
                            popup1.setPopupListener(new OnPopupListener() {
                                @Override
                                public void onNext() {
                                    popup1.dismiss();
                                }

                                @Override
                                public void onClose() {

                                }
                            });
                            popup1.setHideClose(true);
                            new XPopup.Builder(mActivity)
                                    .dismissOnBackPressed(false)
                                    .dismissOnTouchOutside(false)
                                    .setPopupCallback(new XPopupCallback() {
                                        @Override
                                        public void onCreated() {

                                        }

                                        @Override
                                        public void beforeShow() {

                                        }

                                        @Override
                                        public void onShow() {
                                            NativeAdvertManager.getInstance().loadExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_COMMON, new InteractionAdListener() {
                                                @Override
                                                public void onRenderSuccess(View view) {
                                                    popup1.addAdvertView(view);
                                                }

                                                @Override
                                                public void onError() {
                                                    popup1.loadAdvertFail();
                                                }
                                            });
                                        }

                                        @Override
                                        public void onDismiss() {

                                        }

                                        @Override
                                        public boolean onBackPressed() {
                                            return false;
                                        }
                                    })
                                    .asCustom(popup1)
                                    .show();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {

                    }
                });
            }

            @Override
            public void onAdClick() {

            }

            @Override
            public void onVideoComplete() {

            }

            @Override
            public void onVideoError() {

            }
        });
        reportAdvertAction(TrackConstants.ACTION_HOME_BUBBLE_DOUBLE, TrackConstants.NOTE_HOME_BUBBLE_DOUBLE);
    }


    /**
     * 检查泡泡翻倍次数是否超过
     */
    public void checkBubbleDoubleStatus(String goldNumber, int randomMultiple) {
        HttpData.getInstance().getBubbleDoubleStatus(new AbsCallback<BaseData<ButtleDoubleStatus>>() {
            @Override
            public void onRealSuccess(BaseData<ButtleDoubleStatus> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                if (data.getData().isStatus()) {
                    showGoldDoublePop(goldNumber, randomMultiple);
                } else {
                    showButtleLimit();
                }
            }
        });
    }

    /**
     * 泡泡翻倍限制弹框
     */
    private void showButtleLimit() {
        ButtleLimitPopup popup = new ButtleLimitPopup(mActivity);
        popup.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                if (ShuaApplication.game_status && !CommitUtils.isCloseGame()) {
                    if (mActivity instanceof MainActivity) {
                        ((MainActivity) mActivity).openGame();
                    }
                }
            }

            @Override
            public void onClose() {

            }
        });
        new XPopup.Builder(mActivity)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated() {

                    }

                    @Override
                    public void beforeShow() {

                    }

                    @Override
                    public void onShow() {
                        NativeAdvertManager.getInstance().loadExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_WITHDRAW, 270, new InteractionAdListener() {
                            @Override
                            public void onRenderSuccess(View view) {
                                popup.addAdvertView(view);
                            }

                            @Override
                            public void onError() {
                                popup.loadAdvertFail();
                            }
                        });
                    }

                    @Override
                    public void onDismiss() {

                    }

                    @Override
                    public boolean onBackPressed() {
                        return false;
                    }
                })
                .asCustom(popup)
                .show();
    }

    /**
     * 金豆随机的倍数
     *
     * @return
     */
    private int getRandomMultiple() {
        int min = ShuaApplication.multiple_min;
        int max = ShuaApplication.multiple_max;
        return min + (int) (Math.random() * (max - min + 1));
    }

    /**
     * 点击领取金豆
     *
     * @param childIndex
     * @param goldNumber
     */
    private synchronized void requestGoldPre(int childIndex, String goldNumber) {
        if (lastTime == 0 || System.currentTimeMillis() - lastTime >= 3000) {
            lastTime = System.currentTimeMillis();
            if (imgButtleGuide.getVisibility() == View.VISIBLE) {
                Store.getInstance().setGoldGuideEnable(false);
                imgButtleGuide.setVisibility(View.GONE);
            }
            requestGoldReward(childIndex, goldNumber);
        } else {
            if (!isRequesting) {
                MyToast.showToast(mActivity, "点击太频繁，请稍后再试");
            }
        }
    }

    private boolean isRequesting = false;

    private synchronized void requestGoldReward(int childIndex, String goldNumber) {
        isRequesting = true;
        HttpData.getInstance().requestGoldReward(goldNumber, new AbsCallback<BaseData<GoldBean>>() {
            @Override
            public void onRealSuccess(BaseData<GoldBean> goldBean) {
                String value = goldBean.getData().getValue();
                if (!TextUtils.isEmpty(value)) {
                    showGoldPopup(childIndex, value);
                } else {
                    isRequesting = false;
                }
            }

            @Override
            public void onSuccess(BaseData<GoldBean> data) {
//                super.onSuccess(data);
                if (data == null) {
                    isRequesting = false;
                    return;
                }
                if (data.isStatus() && data.getCode() == 200) {
                    onRealSuccess(data);
                } else {
                    isRequesting = false;
                    MyToast.showToast(mActivity, data.getMessage());
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                isRequesting = false;
            }
        });
        reportAdvertAction(TrackConstants.ACTION_HOME_BUBBLE, TrackConstants.NOTE_HOME_BUBBLE);
    }

    private void reportAdvertAction(String action, String note) {
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_HOME, action, note);
    }

    private void autoPlayClick(boolean autoPlay) {
        if (!isShowAutoPlayView) return;
        isAutoPlay = autoPlay;
        if (isAutoPlay) {
            ToastUtil.show(mActivity, "已为你开启自动播放模式");
        } else {
            ToastUtil.show(mActivity, "已关闭自动播放模式");
        }
        switchAutoPlayImage();
    }

    private void initVideoPlayView(View root) {
        videoPlayView = root.findViewById(R.id.video_play_detail_view);
        videoPlayView.setOnStsInfoExpiredListener(new OnStsInfoExpiredListener() {
            @Override
            public void onTimeExpired() {
                //刷新获取STS
                StsInfoManager.getInstance().refreshStsToken(new MyStsResultListener(HomeFragment.this));
            }

            @Override
            public StsTokenInfo refreshSts() {
                return StsInfoManager.getInstance().refreshStsToken();
            }
        });
        videoPlayView.setOnItemClickListener(new AlivcVideoPlayView.OnItemClickListener() {
            @Override
            public void onJumpComment(String videoId, String headerUrl, int commentCount, int position) {
                // showBottomComment(videoId, headerUrl);
                if (isAutoPlay) {
                    autoPlayClick(false);
                }
                if (mActivity instanceof MainActivity) {
                    ((MainActivity) mActivity).showBottomComment(videoId, headerUrl, commentCount, position);
                }
            }

            @Override
            public void onJumpShare() {
                if (isAutoPlay) {
                    autoPlayClick(false);
                }
            }

            @Override
            public void onJumpAdDetail(String link_type, String url) {
                LogUtil.d("onJumpAdDetail");
                if (!isAutoPlay) {
                    autoPlayClick(true);
                }
                reportAdvertAction(AdvertReport.EventType.VideoClick);
                if ("2".equals(link_type)) {
                    AdDownloadManager.getInstance().installApk(mActivity, url);
                } else {
                    ARouter.getInstance().jumpH5(mActivity, url);
                }
            }

            @Override
            public void onAdPlayStart() {
                reportThirdAdvertAction(AdvertReport.EventType.VideoStart);
            }

            @Override
            public void onAdPlayPaused() {
                reportThirdAdvertAction(AdvertReport.EventType.VideoPause);
            }

            @Override
            public void onAdPlayComplete() {
                reportThirdAdvertAction(AdvertReport.EventType.VideoEnd);
            }
        });

        videoPlayView.setOnVideoDeleteListener(video -> {

        });

        videoPlayView.setOnAdStatusListener(new AlivcVideoListView.OnAdStatusListener() {
            @Override
            public void VideoStart() {
                reportAdvertAction(AdvertReport.EventType.VideoStart);
            }

            @Override
            public void VideoStop() {
                reportAdvertAction(AdvertReport.EventType.VideoStop);
            }

            @Override
            public void VideoEnd() {
                reportAdvertAction(AdvertReport.EventType.VideoEnd);
            }
        });
        videoPlayView.setOnPlayStatusListener(new AlivcVideoListView.OnPlayStatusListener() {
            @Override
            public void start() {
                startTime = System.currentTimeMillis();
                if (tempTimeDefault > 0) {
                    if (ctdView.isAnimationRun()) {
                        ctdView.resume();
                    } else {
                        ctdView.start(tempTimeDefault);
                    }
                }
                if (videoPlayView != null) {
                    videoPlayView.start();
                }
            }

            @Override
            public void stop(IVideoSourceModel videoListBean, int position) {
                long end_timestamp = System.currentTimeMillis();
                ctdView.pause();
                if (videoPlayView != null) {
                    videoPlayView.stop();
                }
                if (videoListBean == null) {
                    return;
                }
                if (!Store.getInstance().isLogin()) {
                    return;
                }
                if (videoListBean instanceof LittleMineVideoInfo.VideoListBean) {
                    LittleMineVideoInfo.VideoListBean video = (LittleMineVideoInfo.VideoListBean) videoListBean;
                    if (video.getType() != Constants.AD.ad_item_type && video.getType() != 100) {
                        ReportVideoTagManager.getInstance().reportVideoTag(video.getId(), startTime, end_timestamp);
                    }
                }
            }

            @Override
            public void onCompletion() {
//                if (!GuideEntity.isGuide) {
                ctdView.pause();
//                }
                //调用太频繁，开关状态字段移至首页接口
//                fetchConfig();
                if (videoPlayView != null) {
                    videoPlayView.onCompletion();
                    if (isAutoPlay) {
                        // 关闭评论弹窗
                        if (mActivity instanceof MainActivity) {
                            ((MainActivity) mActivity).closeCommentDialog();
                        }
                        videoPlayView.playNext();
                    }
                }
            }

        });

        videoPlayView.setOnViewPagerListener(position -> {
            currentPosition = position;
            //如果滑动就不需要新手提示:上滑查看视频手势
            if (Store.getInstance().isLogin() && Store.getInstance().getNEW_LOCK_VIDEO() && Store.getInstance().getIsNewUser()) {
                Store.getInstance().setNEW_LOCK_VIDEO(false);
            }

            //滑动至第三个视频
            if (Store.getInstance().isLogin() && Store.getInstance().getNEW_DOUCLICK() && Store.getInstance().getIsNewUser()) {
                if (position == 2) {
                    initDouClickGuide();
                }
            }

            // 第二页弹出自动播放引导
            if (position == 1 && Store.getInstance().isShowGuideAutoPlay() && isShowAutoPlayView) {
                showAutoPlayGuide(true);
            }

            if (videoPlayView != null && position > 1 && videoPlayView.getData().size() > position) {
                int type = videoPlayView.getData().get(position).getType();
                if (type == 100 || type == Constants.AD.ad_item_type) {
                    if (isAutoPlay) {
                        autoPlayClick(false);
                    }
                }
            }
        });

        viewGuide.setOnClickListener(v -> {
            Store.getInstance().setIsGuideAutoPlay(false);
            showAutoPlayGuide(false);
        });

        if (videoPlayView != null) {
            float screenWidth = ScreenUtils.getWidth(mActivity);
            float screenHeight = ScreenUtils.getRealHeight(mActivity);
            if (screenHeight / screenWidth > 2) {
                int viewHeight = (int) (screenHeight - ScreenUtils.getNavigationHeight(mActivity));
                ViewGroup.LayoutParams layoutParams = videoPlayView.getLayoutParams();
                layoutParams.height = viewHeight;
                videoPlayView.setLayoutParams(layoutParams);
            }
            videoPlayView.setOnRefreshDataListener(new MyRefreshDataListener(this));
            videoPlayView.onRefresh();
        }
    }

    public void autoClickAd() {
        if (videoPlayView == null || videoPlayView.getVideoListView() == null) return;
        RecyclerViewEmptySupport recyclerView = videoPlayView.getVideoListView().getRecycler();
        for (int i = 0; i < recyclerView.getChildCount(); i++) {
            View childView = recyclerView.getChildAt(i);
            if (childView != null && childView.getTag() != null && childView.getTag().toString().equals(currentPosition + "")) {
                FrameLayout flContainer = childView.findViewById(R.id.video_layout);
                if (flContainer != null && flContainer.getChildCount() > 0) {
                    View adView = flContainer.getChildAt(0);
                    if (adView != null && adView instanceof ViewGroup) {
                        traverseView((ViewGroup) adView);
                    }
                }
            }
        }
    }

    // todo 广告新增
    public void traverseView(ViewGroup child) {
        for (int i = child.getChildCount() - 1; i >= 0; i--) {
            View view = child.getChildAt(i);
            if (view instanceof ViewGroup) {
                traverseView((ViewGroup) view);
            }

            if (view instanceof ViewStub) {
                View stubView = ((ViewStub) view).inflate();
                if (stubView instanceof ViewGroup) {
                    traverseView((ViewGroup) stubView);
                }
            }

            if (view instanceof TextView && view.getId() == R.id.tt_bu_download) {
                view.performClick();
                break;
            }

            if (view instanceof WebView && (view.getClass().getName().contains("qq") || view.getClass().getName().contains("tencent"))) {
                WebView webView = ((WebView) view);
                if (webView.getChildCount() == 0) {
                    clickView(view, view.getWidth() / 2, view.getHeight() / 2);
                } else {
                    for (int j = 0; j < webView.getChildCount(); j++) {
                        View webChild = webView.getChildAt(j);
                        // webChild.performClick();
                        clickView(webChild, webChild.getWidth() / 2, webChild.getHeight() / 2);
                    }
                }
                break;
            }

            if (view instanceof SSWebView) {
                SSWebView ssWebView = (SSWebView) view;
                int contentHeight = ssWebView.getContentHeight();

                int width = ssWebView.getWidth();
                int height = ssWebView.getHeight();

                // 默认点击
                int clickX = DensityUtil.dip2px(mActivity, 48) + new Random().nextInt(20);
                int clickY = height - contentHeight / 2 + new Random().nextInt(48);

                clickView(ssWebView, clickX, clickY);

                break;
            }
        }
    }

    // todo 广告新增
    public void clickView(View view, float x, float y) {
        long downTime = SystemClock.uptimeMillis();
        final MotionEvent downEvent = MotionEvent.obtain(
                downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0);
        downTime += 10;
        final MotionEvent upEvent = MotionEvent.obtain(
                downTime, downTime, MotionEvent.ACTION_UP, x, y, 0);
        view.onTouchEvent(downEvent);
        view.onTouchEvent(upEvent);
        downEvent.recycle();
        upEvent.recycle();
    }

    private void jumpToRecorder() {
    }

    private LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();

    private void changeVideoAutoPlay(boolean autoPlayStatus) {
        isShowAutoPlayView = autoPlayStatus;
        autoPlay.setVisibility(autoPlayStatus ? View.VISIBLE : View.INVISIBLE);
        switchAutoPlayImage();
    }

    // 切换自动播放
    private void switchAutoPlayImage() {
        autoPlay.setImageResource(!isAutoPlay ? R.drawable.auto_play_sel : R.drawable.auto_play_nor);
    }

    private void showAutoPlayGuide(boolean visible) {
        ivGuide1.setVisibility(visible ? View.VISIBLE : View.GONE);
        viewGuide.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    // 数据
    private void fetchHomeData(int page) {
        if (page == 1) {
            isFirstLoadData = true;
        }
        homeViewModel.fetchHomeData(page, pageSize * MAY_REQUEST_AD_NUM);
        if (videoPlayView != null) {
            videoPlayView.showLoading();
        }
    }

    //登入提示窗
    private void showRedDialog() {
        LoginPopup giftSignPopup = new LoginPopup(mActivity);
        giftSignPopup.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                giftSignPopup.dismiss();
                startActivity(new Intent(mActivity, LoginActivity.class));
            }

            @Override
            public void onClose() {

            }
        });
        new XPopup.Builder(mActivity)
                .asCustom(giftSignPopup)
                .show();

    }

    private void reportAdvertAction(AdvertReport.EventType state) {
        if (videoPlayView != null && videoPlayView.getCurrentModel() instanceof LittleMineVideoInfo.VideoListBean) {
            LittleMineVideoInfo.VideoListBean mo = (LittleMineVideoInfo.VideoListBean) videoPlayView.getCurrentModel();
            if (mo.getType() == Constants.AD.ad_item_type) {
                AdvertReportManager.getInstance().reportAdvertAction(mo.getId(), mo.uuid, state, "2");
            }
        }
    }

    private void reportThirdAdvertAction(AdvertReport.EventType state) {
        if (videoPlayView != null && videoPlayView.getCurrentModel() instanceof LittleMineVideoInfo.VideoListBean) {
            LittleMineVideoInfo.VideoListBean mo = (LittleMineVideoInfo.VideoListBean) videoPlayView.getCurrentModel();
            if (mo.getType() == 100) {
                AdReportManager.getInstance().reportAdvertAction(mo.getPlanId(), mo.getUuidThirdAdvert(), state, 2 + "");
            }
        }
    }

    private Handler playHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (videoPlayView != null) {
                if (videoPlayView.isOnBackground() || !videoPlayView.isPause()) {
                    videoPlayView.onPause();
                }
            }
        }
    };


    @Override
    public void onDestroy() {
        if (videoPlayView != null) {
            videoPlayView.onDestroy();
        }
        if (subscribe != null) {
            subscribe.dispose();
        }
        if (mOxWallView != null) {
            mOxWallView.destroy();
        }
        PhoneCallManager.getInstance().deleteCallListener(this);
        super.onDestroy();
    }

    @Override
    public void onCallRinging() {
        if (videoPlayView != null) {
            videoPlayView.onPause();
        }
    }

    @Override
    public void onCallOffHook() {
    }

    @Override
    public void onCallIdle() {
    }

    public void onReNetConnected() {
        if (videoPlayView != null && videoPlayView.isRefreshing()) {
            videoPlayView.onRefresh();
        }
    }

    private static class MyStsResultListener implements OnStsResultListener {
        WeakReference<HomeFragment> weakReference;

        MyStsResultListener(HomeFragment activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onSuccess(StsTokenInfo tokenInfo) {
            HomeFragment videoListActivity = weakReference.get();
            // videoListActivity.videoPlayView刷新sts信息
            if (videoListActivity.videoPlayView != null) {
                videoListActivity.videoPlayView.refreshStsInfo(tokenInfo);
            }
        }

        @Override
        public void onFail() {

        }
    }

    public static class MyRefreshDataListener implements AlivcVideoListView.OnRefreshDataListener {
        WeakReference<HomeFragment> weakReference;

        MyRefreshDataListener(HomeFragment activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onRefresh() {
            if (weakReference == null) {
                return;
            }
            page = 1;
            isLoadFirstPageAdData = false;
            lastAdPosition = 0;
            HomeFragment activity = weakReference.get();
            if (activity != null) {
                activity.fetchHomeData(page);
            }
        }

        @Override
        public void onLoadMore() {
            page++;
            if (weakReference == null) {
                return;
            }
            HomeFragment activity = weakReference.get();
            if (activity != null) {
                activity.fetchHomeData(page);
            }
        }
    }

    private void reportRequestStart(int request_num) {
        ActionThirdReportManager.getInstance().reportRequestStart(1, 3, mCodeId, request_num);
    }

    private void reportRequestSucc(int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(1, 3, mCodeId, return_num);
    }

    private void reportRequestFail(int request_num, String error_code, String error_msg) {
        ActionThirdReportManager.getInstance().reportRequestFail(1, 3, mCodeId, request_num, error_code, error_msg);
    }

    private void reportRequestRend(String error_code, String error_msg) {
        ActionThirdReportManager.getInstance().reportRequestRend(1, 3, mCodeId, error_code, error_msg);
    }

    private void loadAdvertList() {
//        boolean isLogin = Store.getInstance().isLogin();
//        if (!isLogin) {
//            //未登录，采用匿名代码位
//            loadExpressDrawNativeAd("945413530");
//            return;
//        }
        if (ShuaApplication.drawConfig == null) {
            loadExpressDrawNativeAd("945413530");
            return;
        }
        AdvertConfigBean advertConfig = ShuaApplication.drawConfig.getAdvertConfig();
        if (advertConfig == null) {
            loadExpressDrawNativeAd("945413530");
            return;
        }
        String codeId = advertConfig.getOrigin_id();
        if (advertConfig.isSelf()) {
            loadSelfAdvert(codeId);
        } else {
            loadExpressDrawNativeAd(codeId);
        }
    }

    private String uuiThirdAdvert;

    private void loadExpressDrawNativeAd(String codeId) {
        ttNativeExpressAds = new ArrayList<>();
        uuiThirdAdvert = Util.getUUID32();

        //step3:创建广告请求参数AdSlot,具体参数含义参考文档
        float expressViewWidth = UIUtils.getScreenWidthDp(ShuaApplication.getContext());
        float expressViewHeight = UIUtils.getHeight(this.mActivity) - 20;
//        boolean isLogin = Store.getInstance().isLogin();
//        if (isLogin) {
//            if (ShuaApplication.drawConfig != null) {
//                codeId = ShuaApplication.drawConfig.getDrawId();
//            }
//        } else {
//            //未登录，采用匿名代码位
//            codeId = "945413530";
//        }
        if (TextUtils.isEmpty(codeId)) {
            codeId = "945413530";
        }
        mCodeId = codeId;
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId)
                .setSupportDeepLink(true)
                .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight) //期望模板广告view的size,单位dp
                .setAdCount(MAY_REQUEST_AD_NUM) //请求广告数量为1到3条
                .build();
        //step4:请求广告,对请求回调的广告作渲染处理
        mTTAdNative.loadExpressDrawFeedAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                reportRequestFail(MAY_REQUEST_AD_NUM, code + "", message);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.isEmpty()) {
                    return;
                }
                reportRequestSucc(ads.size());
                for (final TTNativeExpressAd ad : ads) {
                    ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                        @Override
                        public void onAdClicked(View view, int type) {
                            reportAdvertAction(TrackConstants.ACTION_HOME_DETAILS, TrackConstants.NOTE_HOME_DETAILS);
                            reportThirdAdvertAction(AdvertReport.EventType.VideoClick);
                        }

                        @Override
                        public void onAdShow(View view, int type) {
                        }

                        @Override
                        public void onRenderFail(View view, String msg, int code) {
                            reportRequestRend(code + "", msg);
                        }

                        @Override
                        public void onRenderSuccess(View view, float width, float height) {
                            addAdData(ad);
//                            ttNativeExpressAds.add(ad);
//                            if (page == 1 && !isLoadFirstPageAdData) {
//                                // 首次插入广告数据
//                                insertFirstAdData(ads);
//                                ttNativeExpressAds = new ArrayList<>();
//                                isLoadFirstPageAdData = true;
//                                loadAdvertList();
//                            }
                        }
                    });
                    ad.render();
                }
            }
        });

        reportRequestStart(MAY_REQUEST_AD_NUM);
    }

    // 加载广告流数据
    private void loadSelfAdvert(String planId) {
        HttpData.getInstance().getPlanById(planId, new ACallback<BaseData<AdvertList>>() {
            @Override
            public void onSuccess(BaseData<AdvertList> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                AdvertList advertList = data.getData();
                if (advertList.getItems() == null || advertList.getItems().size() < 1) {
                    return;
                }
                adExpressList = advertList.getItems();
                adExpressUUId = advertList.getUuid();
                addSelfAdData(advertList.getItems(), advertList.getUuid());
//                // 第一页数据 需要自动插数据
//                if (page == 1 && !isLoadFirstPageAdData) {
//                    insertOwnFirstAdData(advertList.getItems(), advertList.getUuid());
//                    adExpressList = new ArrayList<>();
//                    isLoadFirstPageAdData = true;
////                    loadSelfAdvert(planId);
//                    loadAdvertList();
//                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });
    }

    private void insertVideo(int video_id) {
        HttpData.getInstance().getVideoInfo(video_id, new ACallback<BaseData<VideoInfo>>() {
            @Override
            public void onSuccess(BaseData<VideoInfo> data) {
                if (data != null && data.isStatus() && data.getData() != null) {
                    LogUtil.d(data.getData().toString());
                    LittleMineVideoInfo.VideoListBean videoListBean = new LittleMineVideoInfo.VideoListBean();
                    VideoInfo dataBean = data.getData();
                    videoListBean.setVideoId(dataBean.getMedia_id());
                    videoListBean.setVideoUrl(dataBean.getMedia_url());
                    videoListBean.setFirstFrameUrl(dataBean.getAvatar());
                    videoListBean.setDescription(dataBean.getDescription());
                    BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
                    if (dataBean.getUser() != null) {
                        userBean.setAvatarUrl(dataBean.getUser().getAvatar());
                        userBean.setUserId(dataBean.getUser().getId() + "");
                        userBean.setUserName(dataBean.getUser().getName());
                    }
                    videoListBean.setUser(userBean);
                    videoListBean.setType(dataBean.getType());
                    videoListBean.setId(dataBean.getId());
                    videoListBean.setShareUrl(dataBean.getMedia_url());
                    videoListBean.setTitle(dataBean.getTitle());
                    videoListBean.setLocation(dataBean.getLocation());
                    videoListBean.setCommentCount(dataBean.getComment_count());
                    videoListBean.setPraiseCount(dataBean.getPraise_count());
                    videoListBean.setForwardCount(dataBean.getForward_count());
                    videoListBean.setLength(dataBean.getLength());
                    videoListBean.setFollow_status(dataBean.getFollow_status());
                    videoListBean.setLove(dataBean.getIs_praise_user());
                    videoListBean.setServer_time(dataBean.getServer_time());
                    videoListBean.setAdvert_url(dataBean.getAdvert_url());
                    videoListBean.setAdvert_html(dataBean.getAdvert_html());
                    videoListBean.setAdvert_charge_type(dataBean.getAdvert_charge_type());
                    if (videoPlayView != null && videoPlayView.getAdapter() != null) {
                        LittleVideoListAdapter adapter = videoPlayView.getAdapter();
                        List<IVideoSourceModel> dataList = videoPlayView.getData();
                        if (dataList.size() != 0) {
                            dataList.add(adapter.getCurrentHolder().getAdapterPosition(), videoListBean);
                            adapter.notifyItemInserted(adapter.getCurrentHolder().getAdapterPosition());
                            adapter.notifyDataSetChanged();
                            videoPlayView.addAdPlayer(videoListBean);
                        } else {
                            //首页没数据保存
                            isNoticeVideo = true;
                            HomeFragment.this.videoListBean = videoListBean;
                        }
                    }
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });


    }

    /**
     * @param items
     */
    private void insertOwnFirstAdData(List<AdvertInfo> items, String uuId) {
        LittleVideoListAdapter adapter = videoPlayView.getAdapter();
        if (videoPlayView != null && adapter != null) {
            List<IVideoSourceModel> dataList = videoPlayView.getData();
            int size = dataList.size();
            if (dataList != null && items != null) {
                if (size == pageSize * MAY_REQUEST_AD_NUM) {
                    for (int i = 0; i < items.size(); i++) {
                        LittleMineVideoInfo.VideoListBean bean = coverOwnAdToVideoBean(items.get(i), uuId);
                        dataList.add(size, bean);
                        adapter.notifyItemInserted(size);
                        videoPlayView.addAdPlayer(bean);
                        size -= pageSize;
                    }
                } else {
                    for (int i = 0; i < items.size(); i++) {
                        int index = pageSize * (i + 1) + i;
                        if (index <= dataList.size()) {
                            LittleMineVideoInfo.VideoListBean bean = coverOwnAdToVideoBean(items.get(i), uuId);
                            dataList.add(index, bean);
                            adapter.notifyItemInserted(size);
                            videoPlayView.addAdPlayer(bean);
                        }
                    }
                }
            }
        }
    }

    private LittleMineVideoInfo.VideoListBean coverOwnAdToVideoBean(AdvertInfo ad, String uuId) {
        LittleMineVideoInfo.VideoListBean videoBean = new LittleMineVideoInfo.VideoListBean();
        videoBean.setVideoId(ad.plan_id + "" + System.identityHashCode(ad));
        videoBean.setId(ad.plan_id);
        videoBean.uuid = uuId;
        videoBean.setVideoUrl(ad.origin_url);
        videoBean.setFirstFrameUrl(ad.thumbnail);
        videoBean.setType(Constants.AD.ad_item_type);
        BaseVideoSourceModel.UserBean userBean = new BaseVideoSourceModel.UserBean();
        if (!TextUtils.isEmpty(ad.nick_name)) {
            userBean.setUserName(ad.nick_name);
        }
        if (!TextUtils.isEmpty(ad.avatar)) {
            userBean.setAvatarUrl(ad.avatar);
        }
        if (!TextUtils.isEmpty(ad.details)) {
            videoBean.setDescription(ad.details);
        }
        if (!TextUtils.isEmpty(ad.click_url)) {
            videoBean.jump_url = ad.click_url;
        }
        videoBean.setUser(userBean);
        videoBean.media_type = ad.media_type;
        videoBean.action_type = ad.action_type;
        videoBean.link_type = ad.link_type;
        return videoBean;
    }

    /**
     * @param adList
     */
    private void insertFirstAdData(List<TTNativeExpressAd> adList) {
        LittleVideoListAdapter adapter = videoPlayView.getAdapter();
        if (videoPlayView != null && adapter != null) {
            List<IVideoSourceModel> dataList = videoPlayView.getData();
            int size = dataList.size();
            if (adList != null) {
                if (size == pageSize * MAY_REQUEST_AD_NUM) {
                    for (int i = 0; i < adList.size(); i++) {
                        dataList.add(size, coverAdToVideoBean(adList.get(i)));
                        adapter.notifyItemInserted(size);
                        size -= pageSize;
                    }
                } else {
                    for (int i = 0; i < adList.size(); i++) {
                        int index = pageSize * (i + 1) + i;
                        if (index <= dataList.size()) {
                            dataList.add(index, coverAdToVideoBean(adList.get(i)));
                            adapter.notifyItemInserted(size);
                        }
                    }
                }
            }
        }
    }

    private static int lastAdPosition = 0;

    private void addAdData(TTNativeExpressAd ad) {
        try {
            LittleVideoListAdapter adapter = videoPlayView.getAdapter();
            if (videoPlayView.getAdapter() == null || videoPlayView.getData().size() < 1 || ad == null) {
                return;
            }
            List<IVideoSourceModel> dataList = videoPlayView.getData();
            int tempPosition;
            if (lastAdPosition == 0) {
                tempPosition = lastAdPosition + pageSize;
            } else {
                tempPosition = lastAdPosition + pageSize + 1;
            }
            if (tempPosition <= videoPlayView.getData().size()) {
                lastAdPosition = tempPosition;
                dataList.add(lastAdPosition, coverAdToVideoBean(ad));
                adapter.notifyItemInserted(lastAdPosition);
            }
        } catch (Exception ignored) {

        }
    }

    private void addSelfAdData(List<AdvertInfo> items, String uuId) {
        try {
            LittleVideoListAdapter adapter = videoPlayView.getAdapter();
            if (videoPlayView.getAdapter() == null || videoPlayView.getData().size() < 1 || items == null || items.size() < 1) {
                return;
            }
            for (AdvertInfo ad : items) {
                List<IVideoSourceModel> dataList = videoPlayView.getData();
                int tempPosition;
                if (lastAdPosition == 0) {
                    tempPosition = lastAdPosition + pageSize;
                } else {
                    tempPosition = lastAdPosition + pageSize + 1;
                }
                if (tempPosition <= videoPlayView.getData().size()) {
                    lastAdPosition = tempPosition;
                    LittleMineVideoInfo.VideoListBean bean = coverOwnAdToVideoBean(ad, uuId);
                    dataList.add(lastAdPosition, bean);
                    adapter.notifyItemInserted(lastAdPosition);
                    videoPlayView.addAdPlayer(bean);
                }
            }
        } catch (Exception ignored) {

        }
    }

    private LittleMineVideoInfo.VideoListBean coverAdToVideoBean(TTNativeExpressAd ad) {
        LittleMineVideoInfo.VideoListBean videoBean = new LittleMineVideoInfo.VideoListBean();
        videoBean.setVideoId("fake id");
        videoBean.setVideoUrl("fake url");
        videoBean.setType(100);
        videoBean.setAd(ad);
        videoBean.setUuidThirdAdvert(uuiThirdAdvert);
        String planId = System.identityHashCode(ad) + "";
        videoBean.setPlanId(planId);
        return videoBean;
    }

    /**
     * 接收推送通知
     *
     * @param extraBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onVideoIdEvent(ExtraBean extraBean) {
        if (extraBean.getType() == 1) {
            if (extraBean.getOpen_id() == 1) {
                ((MainActivity) mActivity).openHome();
            } else if (extraBean.getOpen_id() == 2) {
                ((MainActivity) mActivity).openGift();
            } else if (extraBean.getOpen_id() == 3) {
                ((MainActivity) mActivity).openMine();
            } else {
                ((MainActivity) mActivity).openHome();
            }
        } else if (extraBean.getType() == 2) {
            Intent intent = new Intent(mActivity, FriendsDetailsActivity.class);
            intent.putExtra("USER_ID", extraBean.getUser_id() + "");
            mActivity.startActivity(intent);
        } else if (extraBean.getType() == 3) {
            insertVideo(extraBean.getVideo_id());
        } else if (extraBean.getType() == 4) {
            if (!Store.getInstance().isLogin()) {
                mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
            } else {
                Intent intent = new Intent(mActivity, H5Activity.class);
                intent.putExtra("money", Constants.H5_URL + "withdraw");
                intent.putExtra("title", "我的钱包");
                mActivity.startActivity(intent);
            }
        } else if (extraBean.getType() == 5) {
            if (!Store.getInstance().isLogin()) {
                mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
            } else {
                Intent intent = new Intent(mActivity, MessageActivity.class);
                mActivity.startActivity(intent);
            }
        } else if (extraBean.getType() == 6) {
            if (!Store.getInstance().isLogin()) {
                mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
            } else {
                Intent intent = new Intent(mActivity, H5Activity.class);
                intent.putExtra("money", Constants.H5_URL + "activity_dwj");
                intent.putExtra("title", "端午活动");
                mActivity.startActivity(intent);
            }
        } else if (extraBean.getType() == 7) {
            if (!Store.getInstance().isLogin()) {
                mActivity.startActivity(new Intent(mActivity, LoginActivity.class));
            } else {
                HttpData.getInstance().requestGoldReward(new AbsCallback<BaseData<GoldBean>>() {
                    @Override
                    public void onRealSuccess(BaseData<GoldBean> goldBean) {
                        String value = goldBean.getData().getValue();
                        if (!TextUtils.isEmpty(value)) {
                            OpenNoticePopup popupView = new OpenNoticePopup(mActivity, value, "开启推送奖励");
                            popupView.setPopupListener(new OnPopupListener() {
                                @Override
                                public void onNext() {
                                    ((MainActivity) mActivity).openHome();
                                    popupView.dismiss();
                                }

                                @Override
                                public void onClose() {

                                }
                            });
                            new XPopup.Builder(mActivity)
                                    .asCustom(popupView)
                                    .show();

                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });

            }
        }
        EventBus.getDefault().removeStickyEvent(extraBean);
    }

    /**
     * 接受更新评论事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateCommentNumberEvent(UpdateCommentNumberEvent event) {
        if (event != null && videoPlayView != null) {
            videoPlayView.updateCommentNumber(event.videoId, event.number, event.position);
            RecyclerView recyclerView = videoPlayView.getVideoListView().getRecycler();
            if (videoPlayView.getVideoListView() != null && recyclerView != null) {
                for (int i = 0; i < recyclerView.getChildCount(); i++) {
                    View child = recyclerView.getChildAt(i);
                    if (child.getTag() != null && child.getTag().toString().equals(event.position + "")) {
                        View tvNum = child.findViewById(R.id.tv_comment_number);
                        if (tvNum != null && tvNum instanceof TextView) {
                            ((TextView) tvNum).setText(NumberUtils.INSTANCE.convertOneDecimalW(event.number));
                        }
                        break;
                    }
                }
            }
        }
    }

    /**
     * 接收任务来的分享事件
     *
     * @param toShare
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onToShareEvent(ToShare toShare) {
        //用户分享
        LittleVideoListAdapter adapter = videoPlayView.getAdapter();
        Store.getInstance().setVideoId(String.valueOf(adapter.getCurrentHolder().getCurrentModel().getId()));
        //广告不弹分享框
        if (videoPlayView != null && adapter.getCurrentHolder().getCurrentModel().getType() != Constants.AD.ad_item_type) {
            new XPopup.Builder(mActivity)
                    .hasShadowBg(false) // 去掉半透明背景
                    .asCustom(new ShareVideoPopup(mActivity, adapter.getCurrentHolder().getCurrentModel().getTitle(), adapter.getCurrentHolder().getCurrentModel().getDescription(), adapter.getCurrentHolder().getCurrentModel().getId() + ""))
                    .show();
        }
    }

    @Override
    public boolean isRegisterEventBus() {
        return true;
    }

    private boolean isAutoShowing = false;

    private synchronized void showAutoPlayPopup() {
        if (isAutoShowing) {
            return;
        }
        isAutoShowing = true;
        autoPlay.postDelayed(() -> isAutoShowing = false, 1000);
        AutoPlayPopup autoPlayPopup = new AutoPlayPopup(mActivity);
        autoPlayPopup.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                RewardAdvertManager.getInstance().showAdvert(mActivity, AdvertConstants.REWARD_TYPE_AUTO, new OnRewardListener() {
                    @Override
                    public void onAdClose() {
                        autoPlayClick(true);
                    }

                    @Override
                    public void onAdClick() {

                    }

                    @Override
                    public void onVideoComplete() {

                    }

                    @Override
                    public void onVideoError() {

                    }
                });

                autoPlayPopup.dismiss();

                reportAdvertAction(TrackConstants.ACTION_HOME_OPEN, TrackConstants.NOTE_HOME_OPEN);
            }

            @Override
            public void onClose() {
                reportAdvertAction(TrackConstants.ACTION_HOME_OFF, TrackConstants.NOTE_HOME_OFF);
                autoPlayPopup.dismiss();
            }
        });

        new XPopup.Builder(mActivity)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated() {

                    }

                    @Override
                    public void beforeShow() {

                    }

                    @Override
                    public void onShow() {
                        NativeAdvertManager.getInstance().loadExpressAd(mActivity, new InteractionAdListener() {
                            @Override
                            public void onRenderSuccess(View view) {
                                autoPlayPopup.addAdvertView(view);
                            }

                            @Override
                            public void onError() {
                                autoPlayPopup.loadAdvertFail();
                            }
                        });

                    }

                    @Override
                    public void onDismiss() {

                    }

                    @Override
                    public boolean onBackPressed() {
                        return false;
                    }
                })
                .asCustom(autoPlayPopup)
                .show();
    }

    /***********************************************新版引导（变态）*************************************************************/

//    public void startGuide2(GuideEntity guideEntity) {
//        if (mActivity instanceof MainActivity) {
//            ((MainActivity) mActivity).startGuide2(guideEntity);
//        }
//    }
    public void showShareDialog() {
        if (videoPlayView != null) {
            videoPlayView.performShareClick();
        }
    }

    public void autoPraise() {
        if (videoPlayView != null) {
            videoPlayView.autoPraise();
        }
    }

//    public void startGuideLevel4() {
//        GuideEntity guideEntity = new GuideEntity();
//        guideEntity.level = GuideEntity.LEVEL_4;
//        GuideEntity.LEVEL4 l4 = new GuideEntity.LEVEL4();
//        l4.viewX = (int) autoPlay.getX();
//        l4.viewY = (int) autoPlay.getY();
//        guideEntity.level4 = l4;
//        startGuide2(guideEntity);
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoldRewardVideoEvent(GuideGoldVideoEvent event) {
        if (event != null && autoPlay != null) {
        }
    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onGuideDisShareEvent(GuideDisShareEvent event) {
//        if (event != null) {
//            if (!GuideEntity.isShare) {
//                GuideEntity guideEntity = new GuideEntity();
//                guideEntity.level = GuideEntity.LEVEL_12;
//                startGuide2(guideEntity);
//            } else {
//                GuideEntity guideEntity = new GuideEntity();
//                guideEntity.level = GuideEntity.LEVEL_15;
//                startGuide2(guideEntity);
//            }
//        }
//    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onGuideAutoPlayEvent(GuideAutoPlayEvent event) {
//        if (event != null && videoPlayView != null) {
//            videoPlayView.playAd();
//
//            GuideEntity guideEntity = new GuideEntity();
//            guideEntity.level = GuideEntity.LEVEL_6;
//            startGuide2(guideEntity);
//        }
//    }

    public void autoJumpNextVideo() {
        if (videoPlayView != null) {
            videoPlayView.playNext();
        }
    }


    /**
     * 新手引导:金豆进度条指引
     */
    public void initRewardGuide() {
        try {
            imgReward.postDelayed(() -> {
                if (Store.getInstance().isLogin() && Store.getInstance().getIsNewUser() && Store.getInstance().getNEW_REWARD() && ctdView != null && ctdView.isShown()) {
                    Animation enterAnimation = new AlphaAnimation(0f, 1f);
                    Animation exitAnimation = new AlphaAnimation(1f, 0f);
                    enterAnimation.setDuration(100);
                    enterAnimation.setFillAfter(true);
                    exitAnimation.setDuration(100);
                    exitAnimation.setFillAfter(true);
                    HighlightOptions options = new HighlightOptions.Builder()
                            .setOnHighlightDrewListener((canvas, rectF) -> {
                                //自定义绘制图形
                                Paint paint = new Paint();
                                paint.setColor(Color.WHITE);
                                paint.setStyle(Paint.Style.STROKE);
                                paint.setStrokeWidth(10);
                                paint.setPathEffect(new DashPathEffect(new float[]{20, 20}, 0));
                                canvas.drawCircle(rectF.centerX(), rectF.centerY(), rectF.width() / 2 + 10, paint);
                            })
                            .build();
                    //用户登录后弹出
                    Builder builder = NewbieGuide.with(HomeFragment.this)
                            .setLabel("initRewardGuide")
                            .alwaysShow(isGuide)//是否每次都显示引导层，默认false，只显示一次
                            .addGuidePage(GuidePage.newInstance()
                                    .addHighLightWithOptions(ctdView, HighLight.Shape.CIRCLE, options)
                                    .addHighLight(ctdView, HighLight.Shape.CIRCLE, new RelativeGuide(R.layout.popup_guide_3, Gravity.TOP))
                                    .setEnterAnimation(enterAnimation)//进入动画
                                    .setExitAnimation(exitAnimation)//退出动画
                            );
                    Controller controller = builder.show();
                    imgReward.postDelayed(() -> {
                        if (controller.isShowing()) {
                            controller.remove();
                        }
                    }, 5000);
                    Store.getInstance().setNEW_REWARD(false);
                }
            }, 2000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新手引导:上滑查看视频手势
     */
    private void initNewLockVideoGuide() {
        try {
            if (Store.getInstance().isLogin() && Store.getInstance().getIsNewUser() && Store.getInstance().getNEW_LOCK_VIDEO() && isSupportVisible()) {
                Animation enterAnimation = new AlphaAnimation(0f, 1f);
                Animation exitAnimation = new AlphaAnimation(1f, 0f);
                enterAnimation.setDuration(100);
                enterAnimation.setFillAfter(true);
                exitAnimation.setDuration(100);
                exitAnimation.setFillAfter(true);
                //用户登录后在第一个视频停留10秒后弹出（若还没有到10秒用户就滑走，此手势不弹出）
                imgReward.postDelayed(() -> {
                    Builder builder = NewbieGuide.with(HomeFragment.this);
                    builder.setLabel("initNewLockVideoGuide")
                            .alwaysShow(isGuide)//是否每次都显示引导层，默认false，只显示一次
                            .addGuidePage(GuidePage.newInstance()
                                    .setLayoutRes(R.layout.popup_guide_1)
                                    .setOnLayoutInflatedListener((view, controller) -> {
                                        //帧动画
                                        view.findViewById(R.id.imgsliding).setBackgroundResource(R.drawable.home_gold_guide_huadong_list);
                                        AnimationDrawable animal = (AnimationDrawable) view.findViewById(R.id.imgsliding).getBackground();
                                        animal.start();
                                    })
                                    .setEnterAnimation(enterAnimation)//进入动画
                                    .setExitAnimation(exitAnimation)//退出动画
                            );
                    Controller controller = builder.show();
                    imgReward.postDelayed(() -> {
                        if (controller.isShowing()) {
                            controller.remove();
                        }
                    }, 5000);


                }, 10000);

                Store.getInstance().setNEW_LOCK_VIDEO(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新手引导:双击屏幕手势 点赞和分享
     */
    public void initDouClickGuide() {
        try {
            Animation enterAnimation = new AlphaAnimation(0f, 1f);
            Animation exitAnimation = new AlphaAnimation(1f, 0f);
            enterAnimation.setDuration(100);
            enterAnimation.setFillAfter(true);
            exitAnimation.setDuration(100);
            exitAnimation.setFillAfter(true);
            HighlightOptions options = new HighlightOptions.Builder()
                    .setOnHighlightDrewListener((canvas, rectF) -> {
                        //自定义绘制图形
                        Paint paint = new Paint();
                        paint.setColor(Color.WHITE);
                        paint.setStyle(Paint.Style.STROKE);
                        paint.setStrokeWidth(10);
                        paint.setPathEffect(new DashPathEffect(new float[]{20, 20}, 0));
                        canvas.drawCircle(rectF.centerX(), rectF.centerY(), rectF.width() / 2 + 10, paint);
                    }).build();
            //滑动至第三个视频
            Builder builder = NewbieGuide.with(HomeFragment.this);
            builder.setLabel("initDouClickGuide")
                    .alwaysShow(isGuide)//是否每次都显示引导层，默认false，只显示一次
                    .addGuidePage(GuidePage.newInstance()
                            .addHighLightWithOptions(getView().findViewById(R.id.guide_love_icon), HighLight.Shape.CIRCLE, options)
                            .addHighLight(getView().findViewById(R.id.guide_love_icon), HighLight.Shape.CIRCLE, new RelativeGuide(R.layout.popup_guide_2, Gravity.LEFT))
                            .setLayoutRes(R.layout.win_guide_2)//引导页布局，点击跳转下一页或者消失引导层的控件id
                            .setOnLayoutInflatedListener((view, controller) -> {
                                view.findViewById(R.id.imgshuanji).setBackgroundResource(R.drawable.home_gold_guide_dianzan_list);
                                AnimationDrawable animal = (AnimationDrawable) view.findViewById(R.id.imgshuanji).getBackground();
                                animal.start();

                            })
                            .setEnterAnimation(enterAnimation)//进入动画
                            .setExitAnimation(exitAnimation)//退出动画
                    );
            //分享引导
            builder.addGuidePage(GuidePage.newInstance()
                    .addHighLightWithOptions(getView().findViewById(R.id.guide_share_icon), HighLight.Shape.CIRCLE, options)
                    .addHighLight(getView().findViewById(R.id.guide_share_icon), HighLight.Shape.CIRCLE, new RelativeGuide(R.layout.popup_guide_4, Gravity.LEFT))
                    .setEnterAnimation(enterAnimation)//进入动画
                    .setExitAnimation(exitAnimation)//退出动画
            ).show();
            Store.getInstance().setNEW_DOUCLICK(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新手引导:引导点击泡泡手势
     */
    public void initClickBubbleGuide() {
        try {
            if (Store.getInstance().isLogin() && Store.getInstance().getIsNewUser() && Store.getInstance().getNEW_CLICKBUBBLE() && isSupportVisible()) {
                Animation enterAnimation = new AlphaAnimation(0f, 1f);
                Animation exitAnimation = new AlphaAnimation(1f, 0f);
                enterAnimation.setDuration(100);
                enterAnimation.setFillAfter(true);
                exitAnimation.setDuration(100);
                exitAnimation.setFillAfter(true);
                Builder builder = NewbieGuide.with(HomeFragment.this)
                        .setLabel("initClickBubbleGuide")
                        .alwaysShow(isGuide)//是否每次都显示引导层，默认false，只显示一次
                        .addGuidePage(GuidePage.newInstance()
                                .setLayoutRes(R.layout.popup_guide_5)//设置引导页布局
                                .setEnterAnimation(enterAnimation)//进入动画
                                .setExitAnimation(exitAnimation)//退出动画
                        );
                Controller controller = builder.show();
                imgReward.postDelayed(() -> {
                    if (controller.isShowing()) {
                        controller.remove();
                    }
                }, 5000);
                Store.getInstance().setNEW_CLICKBUBBLE(false);
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        }
    }
}